# -*- coding: utf-8 -*-
from string import Template

import HTMLTestRunnerCN
from django.shortcuts import render
import json
import datetime
import unittest
import os


def report(request):
    if request.method == "POST":  # 点击生成报告，全选需要生成报告的接口，将接口数据传递到这，进行处理
        arr = request.POST.get('arr')
        data = json.loads(arr)
        for i in data:
            if i['in_type'].upper() == 'POST':
                # 需要将以下地址换成本地地址
                tplFilePath = r'E:/TestPlatform_Cz/InterfaceTestPlatform/TestPlatform_User/Template_Post.py'
                path = r'E:/TestPlatform_Cz/InterfaceTestPlatform/TestPlatform_User/templates/Page/'
                ClassNameList = []
                UrlList = []
                DataList = []
                ClassNameList.append(i['in_mname'])
                UrlList.append(i['in_url'])
                DataList.append(i['in_data'])
                for className in ClassNameList:
                    for urlName in UrlList:
                        for dataList in DataList:
                            now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            filename = 'test_' + str(className) + '.py'  # 必须要以test为开头
                            tplFile = open(tplFilePath, encoding='utf-8')  # windows环境下一定要加上utf-8 避免生成文件中有乱码，影响测试报告
                            gFile = open(path + filename, "w",
                                         encoding='utf-8')  # windows环境下一定要加上utf-8 避免生成文件中有乱码，影响测试报告
                            lines = []
                            tpl = Template(tplFile.read())
                            lines.append(tpl.substitute(
                                now=now,
                                ClassName=className,
                                UrlName=urlName,
                                Data=dataList,
                            ))
                            gFile.writelines(lines)
                            tplFile.close()
                            gFile.close()
                            print('%s文件创建完成' % filename)
                            continue
            elif i['in_type'].upper() == 'GET':
                # 需要将以下地址换成本地地址
                tplFilePath = r'E:/TestPlatform_Cz/InterfaceTestPlatform/TestPlatform_User/Template_Get.py'
                path = r'E:/TestPlatform_Cz/InterfaceTestPlatform/TestPlatform_User/templates/Page/'
                ClassNameList = []
                UrlList = []
                DataList = []
                ClassNameList.append(i['in_mname'])
                UrlList.append(i['in_url'])
                DataList.append(i['in_data'])
                for className in ClassNameList:
                    for params in DataList:
                        for urlName in UrlList:
                            now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            filename = 'test_' + str(className) + '.py'  # 必须要以test为开头
                            tplFile = open(tplFilePath, encoding='utf-8')  # windows环境下一定要加上utf-8 避免生成文件中有乱码，影响测试报告
                            gFile = open(path + filename, "w",
                                         encoding='utf-8')  # windows环境下一定要加上utf-8 避免生成文件中有乱码，影响测试报告
                            lines = []
                            tpl = Template(tplFile.read())
                            lines.append(tpl.substitute(
                                now=now,
                                ClassName=className,
                                Params=params,
                                UrlName=urlName,
                            ))
                            gFile.writelines(lines)
                            tplFile.close()
                            gFile.close()
                            print('%s文件创建完成' % filename)
                            continue
    # 需要将以下地址换成本地地址
    test_dir = r'E:/TestPlatform_Cz/InterfaceTestPlatform/TestPlatform_User/templates/Page/'
    filepath = r'E:/TestPlatform_Cz/InterfaceTestPlatform/report/TestReport.html'  # windows 使用/

    def allcase():
        discover = unittest.defaultTestLoader.discover(test_dir, pattern="test*.py")
        # discover方法筛选出来的用例，循环添加到测试套件中
        suite = unittest.TestSuite()
        suite.addTest(discover)
        print(discover)
        return suite

    fp = open(filepath, 'wb')
    # 定义测试报告的标题与描述
    runner = HTMLTestRunnerCN.HTMLTestReportCN(stream=fp, title=u'接口测试报告')  # description=u'接口测试报告描述'
    runner.run(allcase())
    fp.close()
    # 生成报告后删除对应文件
    files = os.listdir(test_dir)  # 返回文件夹下的文件列表
    for i, name in enumerate(files):  # 逐个遍历
        if name.find(".py") >= 0:  # 判断文件名称中是否包含py字符
            os.remove(test_dir + name)  # 删除操作
    op = open(filepath)
    return render(request, 'Page/Perform_Result.html')
